import { getBaseUrl } from '@/utils/index';
import { sseUrl, colseSseUrl } from '@/api/sse/sse';
import { eventSourceUtil } from '@/utils/eventSource';
import { EventBus } from '@/event-bus.js';

export const sse = {
  data() {
    return {
      insertAudioWaitGen: '',
      insertAudioWaitPlay: '',
      keywordWaitGen: '',
      keywordWaitPlay: '',
      userEnterWaitGen: '',
      userEnterWaitPlay: '',
      randomAudioWaitGen: '',
      randomAudioWaitPlay: '',
      connectAbortController: null,
      connectionAttempts: 0,
      maxConnectionAttempts: 5,
      connectionActive: false
    };
  },
  created() {
    window.addEventListener('beforeunload', this.colseHandler);
    window.addEventListener('pagehide', this.colseHandler);
  },
  destroy() { },
  mounted() { },
  beforeDestroy() {
    this.cleanupConnection();
    window.removeEventListener('beforeunload', this.colseHandler);
    window.removeEventListener('pagehide', this.colseHandler);
  },
  computed: {
    pageConfig() {
      return this.$store.state.page.config;
    },
  },
  methods: {
    cleanupConnection() {
      if (this.connectAbortController) {
        this.connectAbortController.abort();
        this.connectAbortController = null;
      }
      this.connectionActive = false;
      this.connectionAttempts = 0;
    },
    colseHandler(event) {
      if (this.pageConfig.sseChannelId) {
        let baseUrl = getBaseUrl();
        let url = baseUrl + colseSseUrl + this.pageConfig.sseChannelId;
        fetch(url, {
          method: 'POST',
          headers: {},
          keepalive: true  // 关键参数，确保卸载后请求继续
        }).catch(err => {
          console.error('Error closing SSE connection:', err);
        });
      }
    },
    liveAfterHandler() {
      this.liveStatus = 1;
      EventBus.$emit('changeLiveStatus', this.liveStatus);
      this.genRangeNumberAndCountDown(true);
    },
    attemptReconnect() {
      if (this.connectionAttempts >= this.maxConnectionAttempts) {
        console.error('Maximum reconnection attempts reached, giving up');
        EventBus.$emit('connectionFailure', { reason: 'maxAttempts' });
        return;
      }

      this.connectionAttempts++;

      const delay = Math.min(1000 * Math.pow(1.5, this.connectionAttempts - 1), 30000);

      console.log(`Attempting to reconnect (${this.connectionAttempts}/${this.maxConnectionAttempts}) in ${delay}ms`);

      setTimeout(() => {
        if (!this.connectionActive) {
          this.setConnect();
        }
      }, delay);
    },
    setConnect() {
      if (this.connectAbortController) {
        this.connectAbortController.abort();
      }

      const abortController = new AbortController();
      abortController.signal.controller = abortController;
      this.connectAbortController = abortController;

      let baseUrl = getBaseUrl();
      if (process.env.NODE_ENV == "development") {
        baseUrl = "http://127.0.0.1:14000/api/v1";
      }

      let url = baseUrl + sseUrl + this.pageConfig.sseChannelId;

      eventSourceUtil(url, this.connectAbortController.signal, {
        headers: {
          'Cache-Control': 'no-cache',
          'Connection': 'keep-alive'
        }
      }, (response) => {
        if (response.ok && response.status === 200) {
          this.connectionActive = true;
          this.connectionAttempts = 0;
          console.log('SSE connection established');
        } else {
          this.connectionActive = false;
          console.error(`Failed to establish SSE connection: ${response.status}`);

          if (!this.connectAbortController.signal.aborted) {
            this.attemptReconnect();
          }
        }
      }, (event) => {
        if (event.data) {
          try {
            let text = event.data;
            const result = JSON.parse(text);
            const { type, message } = result;

            if (type == 'insertAudioWaitGen') {
              this.insertAudioWaitGen = message;
            } else if (type == 'insertAudioWaitPlay') {
              this.insertAudioWaitPlay = message;
            } else if (type == 'keywordWaitGen') {
              this.keywordWaitGen = message;
            } else if (type == 'keywordWaitPlay') {
              this.keywordWaitPlay = message;
            } else if (type == 'userEnterWaitGen') {
              this.userEnterWaitGen = message;
            } else if (type == 'userEnterWaitPlay') {
              this.userEnterWaitPlay = message;
            } else if (type == 'mainAudioPlayFile') {
              EventBus.$emit('mainAudioPlayFileEvent', result);
            } else if (type == 'playLog') {
              EventBus.$emit('playLogEvent', message);
            } else if (type == 'heartbeat') {
              console.debug('Received heartbeat from server');
            } else if (type == 'startLiveStep') {
              const { startLiveStatusType } = result;
              if (startLiveStatusType == 'suppassMaxCharLengthTimes') {
                this.$modal.closeLoading();
                this.$message.error(message);
                this.cleanupConnection();
              }
              if (startLiveStatusType == 'startErr') {
                this.$modal.closeLoading();
                this.$message.error(message);
                this.cleanupConnection();
              }
              if (startLiveStatusType == 'generating' || startLiveStatusType == 'starting') {
                this.startLiveInstance?.setText(message);
              }
              if (startLiveStatusType == 'playing') {
                this.$modal.closeLoading();
                this.$message.success("开启直播成功");
                this.liveAfterHandler();
              }
            }
          } catch (error) {
            console.error('Error processing SSE message:', error, event.data);
          }
        }
      });
    },
  }
}
